package com.zz.push.server;

import com.zz.push.util.PushClientUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springside.modules.mapper.JsonMapper;

import java.util.HashMap;
import java.util.Map;

public class PushServerHandler extends SimpleChannelInboundHandler<String> {

    private static Logger logger = LoggerFactory.getLogger(PushServerHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Map map = JsonMapper.nonEmptyMapper().fromJson(msg, HashMap.class);

        int code = (int) map.get("code");
        switch (code) {
            case 10000:
                String mac = (String) map.get("mac");
                PushClientUtil.put(ctx.channel(), mac);
                PushClientUtil.pushPersistenceMessage(mac);
                break;
            default:
                break;
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        logger.info("pushClient:" + incoming.remoteAddress() + "在线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        PushClientUtil.remove(incoming);
        logger.info("pushClient:" + incoming.remoteAddress() + "掉线");
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Channel incoming = ctx.channel();
        PushClientUtil.remove(incoming);
        cause.printStackTrace();
        logger.info("pushClient:" + incoming.remoteAddress() + "异常");
        ctx.close();
    }
}
